package com.hymjweb.demo.framework.menu.service;

import com.alibaba.druid.util.StringUtils;
import com.hymjweb.demo.config.shiro.MyShiroRealm;
import com.hymjweb.demo.framework.menu.bean.MenuBean;
import com.hymjweb.demo.framework.menu.mapper.MenuMapper;
import com.hymjweb.demo.framework.menu.bean.MenuPojo;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.hymj.system_maintenance.role.service.RoleService;
import com.hymjweb.demo.hymj.system_maintenance.role_permission.bean.RolePermissionPojo;
import com.hymjweb.demo.hymj.system_maintenance.role_permission.service.RolePermissionService;
import com.hymjweb.demo.hymj.system_maintenance.user_role.bean.UserRolePojo;
import com.hymjweb.demo.hymj.system_maintenance.user_role.service.UserRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.hymjweb.demo.framework.menu
 * @Author: luoge
 * @CreateTime: 2020-10-06 09:27
 * @Description:
 */

@Service
public class MenuService extends BaseService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private MenuMapper menuMapper;

    @Value("${menu.open.account}")
    private String menuOpenAccount;

    public Object getPageList(Map param) {
        // 设置公共查询参数,加上部门
        this.setQueryCommParam(param);
        this.pageListInit(param);
        List list = getNoPageList(param);
        MIniUIGridResultMap resultMap = this.pageToGrid(list);
        return resultMap;
    }

    public List<MenuBean> getNoPageList(Map param){
        return  menuMapper.getNoPageList(param);
    }


    public List<MenuBean> getMenuAndChildrenList() {
        List<MenuBean> list =  menuMapper.getNoPageList(null);

        String czyMobile = this.getLoginCzyMobile();

        String[] openMenuAccountArray = menuOpenAccount.split(",");

        boolean flag = false;
        for(String accountMobile : openMenuAccountArray){
            if(czyMobile.equals(accountMobile)){
                flag = true;
                break;
            }
        }

        if(flag){
            return buildMenuTree(list,"0");
        }

        // 获取用户的角色
        List<UserRolePojo> userRolePojoList = userRoleService.queryUserRoleByUserId(this.getLoginCzyId());
        Set<String> rolePermissionSet = new HashSet<>();
        // 获取用户对应的角色资源
        for(UserRolePojo userRolePojo : userRolePojoList){
            List<RolePermissionPojo> rolePermissionPojoList = rolePermissionService.getRolePermissionListByRoleId(userRolePojo.getRoleId());
            for(RolePermissionPojo pojo : rolePermissionPojoList){
                if(pojo.getResourceTypeId().longValue() == SysConstant.XT_DIC_PERMISSION_TYPE.MEMU.getId()){
                    rolePermissionSet.add(pojo.getPermissionId());
                }
            }
        }

        List<MenuBean> tempList = new ArrayList<>();
        for(MenuBean menuBean : list){
            if(rolePermissionSet.contains(menuBean.getId())){
                tempList.add(menuBean);
            }
        }


        List<MenuBean> treeList =  buildMenuTree(tempList,"0");
        return treeList;
    }

    private List<MenuBean> buildMenuTree(List<MenuBean> menuList, String pid) {
        List<MenuBean> treeList = new ArrayList<>();
        menuList.forEach(menu -> {
            if (StringUtils.equals(pid, menu.getPid())) {
                menu.setChildren(new ArrayList<>());
                menu.setChildren(buildMenuTree(menuList, menu.getId()));
                treeList.add(menu);
            }
        });
        return treeList;
    }


    public int save(MenuBean menuBean) {

        MenuBean pojo = menuMapper.queryMenuPojoById(menuBean.getId());

        int affectRows = 0;

        if(pojo!=null){
            affectRows = menuMapper.update(menuBean);
        }
        else{
            affectRows = menuMapper.insert(menuBean);
        }
        return affectRows;
    }

    public int delete(MenuPojo menuPojo) throws Exception {
        Map<String,Object> param = new HashMap<>();
        param.put("pid",menuPojo.getId());
        List<MenuBean> pojoList = menuMapper.getNoPageList(param);
        if(pojoList!=null &&pojoList.size()>0){
            throw new Exception("删除的菜单项有子菜单，不能直接删除，请先删除子菜单!");
        }
        int affectRows = menuMapper.deleteById(menuPojo.getId());
        return affectRows;
    }

    /**
     * 根据菜单ID检测重复菜单项
     * @param menuId
     * @return
     */
    public MenuBean getMenuById(String menuId) {
        return menuMapper.queryMenuPojoById(menuId);
    }

    /**
     * 添加菜单
     * @param menuBean
     * @return
     */
    public int addMenu(MenuBean menuBean) throws Exception {

        // 1.检测菜单ID是否有重复
        MenuBean currentMenuBean = getMenuById(menuBean.getId());

        if(currentMenuBean!=null){
            throw new Exception("菜单【" + menuBean.getId() + "】,有重复菜单项存在，不能添加！");
        }

        return menuMapper.insert(menuBean);
    }

    /**
     *
     * @param menuBean
     * @return
     */
    public int updateMenu(MenuBean menuBean) throws Exception {
        // 1.检测菜单ID是否存在
        MenuBean currentMenuBean = getMenuById(menuBean.getId());

        if(currentMenuBean==null){
            throw new Exception("菜单【" + menuBean.getId() + "】,有重复菜单项不存在，不能更新！");
        }

        return menuMapper.update(menuBean);
    }
}
